package com.gy.hsim.bservice.framework.mq;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;

/**
 * hession序列化工具类
 * 
 * @author guiyi147
 * 
 */
public class DefaultCodecFactory implements CodecFactory {

	/**
	 * 序列化
	 */
	@Override
	public byte[] serialize(Object obj) throws IOException {
		ByteArrayOutputStream baos = null;
		HessianOutput output = null;
		try {
			baos = new ByteArrayOutputStream(1024);
			output = new HessianOutput(baos);
			output.startCall();
			output.writeObject(obj);
			output.completeCall();
		} catch (final IOException ex) {
			throw ex;
		} finally {
			if (output != null) {
				try {
					baos.close();
				} catch (final IOException ex) {
					throw ex;
				}
			}
		}
		return baos != null ? baos.toByteArray() : null;
	}

	/**
	 * 反序列化
	 */
	@Override
	public Object deSerialize(byte[] in) throws IOException {
		Object obj = null;
		ByteArrayInputStream bais = null;
		HessianInput input = null;
		try {
			bais = new ByteArrayInputStream(in);
			input = new HessianInput(bais);
			input.startReply();
			obj = input.readObject();
			input.completeReply();
		} catch (final IOException ex) {
			throw ex;
		} catch (final Throwable e) {

		} finally {
			if (input != null) {
				try {
					bais.close();
				} catch (final IOException ex) {
					throw ex;
				}
			}
		}
		return obj;
	}

}
